import jwt
from django.core.cache import caches
from rest_framework import serializers
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed, ValidationError

from the_flash.settings import SECRET_KEY
from user.models import UserModel
from utils.user_utils import to_md5_hex, USERNAME_PATTERN


class UserBasicSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserModel
        fields = ('user_id', 'user_name', 'fullname')





class UserPostSerializer(serializers.ModelSerializer):
    repassword = serializers.CharField(write_only=True)
    # code = serializers.CharField(write_only=True)



    def create(self, validated_data):
        # del validated_data['code']
        del validated_data['repassword']
        validated_data['password'] = to_md5_hex(validated_data['password'])
        user = UserModel.objects.create(**validated_data)
        return user
    @staticmethod
    def validate_user_name(user_name):
        if not USERNAME_PATTERN.match(user_name):
            raise ValidationError('用户名由字母数字下划线构成且长度为6-20个字符')
        return user_name

    @staticmethod
    def validate_password(password):
        if len(password) < 8:
            raise ValidationError('用户密码至少8个字符')
        return password

    def validate(self, attrs):
        if attrs['password'] != attrs['repassword']:
            raise ValidationError('用户密码和确认密码需要保持一致')
        # code_from_server = caches['default'].get(attrs['mobile'])
        # code_from_user = attrs['code']
        # if code_from_server != code_from_user:
        #     raise ValidationError('请输入有效的手机验证码')
        return attrs


    class Meta:
        model = UserModel
        fields = '__all__'
        # exclude = ('lastvisit',)


class UserUpdateSerializer(serializers.ModelSerializer):
    oldpassword = serializers.CharField(default='')
    newpassword = serializers.CharField(default='')
    repassword = serializers.CharField(default='')

    class Meta:
        model = UserModel
        exclude = ('password', )
